﻿#include "stdafx.h"
#include "ClassContext.h"
#include "ClassInstanceType.h"
#include "AstFunction.h"
#include "CodeGenerate/ClassMemberGen.h"

ClassContext::ClassContext(SiContext * parent, ClassInstanceType* type) : BlockContext(parent) , _type(type)
{
}

ClassContext::ClassContext(SiContext * parent, CodeGen * gen) : BlockContext(parent)
{
	_type = dynamic_cast<ClassInstanceType*>(gen->type);
	value = gen;
}

CodeGen * ClassContext::findSymbolValue(const std::string & name, bool recursive)
{				   
	assert(_type);

	{	// 先查找本地参数
		auto i = _symbols.find(name);
		if (i != _symbols.end()) {
			return i->second;
		}
	}

	auto i=_type->members.find(name);
	if (i != _type->members.end()) {
		auto *p = new ClassMemberGen();
		p->type = i->second.type;
		p->value = value;
		p->index = i->second.index;
		p->name = name;
		p->classType = _type;
		return p;
	}
	if(parent && recursive)
		return parent->findSymbolValue(name, recursive);
	return nullptr;
}

CodeGen * ClassContext::makeCall(const std::string & name, std::vector<std::pair<std::string, CodeGen*>>& arguments)
{
	auto it=_type->methds.equal_range(name);
	CodeGen* x = nullptr;
	for (auto i = it.first; i != it.second; i++) {
		auto *f = i->second;
		auto *p = f->makeCall(arguments, value);
		if (p) {
			if (x) throw std::runtime_error("多个函数匹配:" + name);
			x = p;
		}
	}

	if (x) return x;
	if (parent) return parent->makeCall(name, arguments);
	return nullptr;
}

